//
// Created by ins on 2021/2/28.
//
#include <json.h>
#include <string>
#include "NpcPresenter.h"
#include "NpcDao.h"
#include "NpcBean.h"

NpcDao *npcDao;
void getNpc(string data, ResData &res_data);
void getNpcMoreInfo(string data, ResData &res_data);

moduleHandler npc_cmds[] = {
    {"01", getNpc},
    {"02", getNpcMoreInfo},
};

void getNpc(string data, ResData &res_data)
{
    list<NpcBean> npcLists;
    NpcBean tmp;
    Json::Value root = Util::init_root(data);
    Json::Value ncpArray = root["npc"];

    cout << "size: " << ncpArray.size() << endl;
    for(int i = 0; i < ncpArray.size();i++)
    {
        if(!ncpArray[i]["id"].isNull())
        {
            NpcBean cxnpc;
            int npc = ncpArray[i]["id"].asInt();
            npcDao->getNpc(npc, cxnpc);
            npcLists.push_back(cxnpc);
        }
    }

    if(npcLists.size() == 0)
    {
        res_data.resp_code = ERRCD_NONPC;
        res_data.resp_data = NONEACKDATA;
    }else{
        res_data.resp_code = ERRCD_PASS;
        res_data.resp_data = "\"npclist\":["+ tmp.npclist_string(npcLists) +"]";
    }
}
void getNpcMoreInfo(string data, ResData &res_data)
{
    NpcMoreInfoBean cxnpc;
    Json::Value root = Util::init_root(data);

    if (!root["id"].isNull())
    {
        int npcId = root["id"].asInt();

        npcDao->getNpcMoreInfo(npcId, cxnpc);
        if (cxnpc.getId() == "")
        {
            res_data.resp_code = ERRCD_NOMAP;
            res_data.resp_data = ERRACKDATA;
        }
        else
        {
            res_data.resp_code = ERRCD_PASS;
            res_data.resp_data = "\"npc\":" + cxnpc.toString();
        }
    }
}

NpcPresenter::NpcPresenter() {}
NpcPresenter::~NpcPresenter() {}

void NpcPresenter::NpcMsgHandler(string cmd, string data, ResData &outData)
{

    cout << "npc: " << data << endl;

    int i = 0;

    if (cmd.empty() || data.empty())
    {
        return;
    }

    for (i = 0; !npc_cmds[i].cmd.empty(); ++i)
    {
        if (cmd != npc_cmds[i].cmd)
            continue;
        break;
    }

    npc_cmds[i].func(data, outData);
}
